/*!
 @header LoginFormViewController.m
 @author 周益
 @version 1.0.0 2013/01/26 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

#import "LoginFormViewController.h"
#import "Helper.h"
#import "MobileFormViewController.h"
#import "Config.h"
#import "Option.h"
#import "JMFBase.h"
#import "DBKit.h"
#import "APService.h"


//  -业务逻辑细节说明-
//
//  @abstract       此为登陆viewcontroller，首先会呈现登录view，然后待用户点击登录时，会向服务器发送登录请求，并且接收到responseData，将responseData存入
//  本地数据库。服务器验证成功后，会有view提示。
//

//  @discussion    

//  @notes          


//  -类修改日志-
//  修改人   修改时间   针对版本   修改描述

@interface LoginFormViewController ()

@end

@implementation LoginFormViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (BOOL)prefersStatusBarHidden
{
    return NO;
}
- (void)viewDidLoad
{
    [super viewDidLoad];

    //背景
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    
    //导航按钮：返回
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    //手机号码textfield背景
    UIImageView *phoneTextFieldImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"com_bg_010"]];
    phoneTextFieldImageView.frame = CGRectMake(10, 15, 300, 45);
    [self.view addSubview:phoneTextFieldImageView];
    
    //密码textfield背景
    UIImageView *passwordTextFieldImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"com_bg_010"]];
    passwordTextFieldImageView.frame = CGRectMake(10, 70, 300, 45);
    [self.view addSubview:passwordTextFieldImageView];
    //手机号码
    _phoneTextField = [Helper textField:CGRectMake(15, 16, 290, 40) byPlaceholder:_L(@"holder_16")];
    _phoneTextField.font = _SYS_FONT_007;
    _phoneTextField.keyboardType = UIKeyboardTypePhonePad;
    [_phoneTextField becomeFirstResponder];
    [self.view addSubview:_phoneTextField];

    //密码
    _passwordTextField = [Helper textField:CGRectMake(15, 71, 290, 40) byPlaceholder:_L(@"holder_15")];
    _passwordTextField.font = _SYS_FONT_007;
    _passwordTextField.keyboardType = UIKeyboardTypeDefault;
    _passwordTextField.secureTextEntry = YES;
    [self.view addSubview:_passwordTextField];
    
    //忘记密码
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"user_btn_007@2x" ofType:@"png"]]];
    imageView.frame = CGRectMake(255, 127, 53, 13);
    imageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGestureLabel = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewEvent:)];
    [imageView addGestureRecognizer:tapGestureLabel];
    [self.view addSubview:imageView];
    
    //登录按钮
    UIButton *loginButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 150, 300, 44)];
    [loginButton setBackgroundImage:[UIImage imageNamed:@"com_btn_006_n"] forState:UIControlStateNormal];
    [loginButton addTarget:self action:@selector(loginButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginButton setTitle:_L(@"btn_yes_18") forState:UIControlStateNormal];
    loginButton.titleLabel.font = _SYS_FONT_009;
    [self.view addSubview:loginButton];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //获取上次登录成功的账号
    NSString *mobileHistory = [[NSUserDefaults standardUserDefaults] objectForKey:@"mobileHistory"];
    
    if (mobileHistory != nil && [mobileHistory length] > 0) {
        _phoneTextField.text = mobileHistory;
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 自定义事件

/*!
 @abstract 忘记密码的触摸事件
 */
- (void)imageViewEvent:(id)sender
{    
    MobileFormViewController *mobileFormVC = [[MobileFormViewController alloc] init];
    [mobileFormVC.navigationItem setTitle:_L(@"vc_title_058")];
    [self.navigationController pushViewController:mobileFormVC animated:YES];
    
    //设置是否是忘记密码还是注册，以便设定密码视图区分是设定注册密码还是找回密码
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isRegisterOrNot"];
}

/*!
 @abstract 返回按钮事件
 */
- (void)backButtonEvent:(id)sender
{
    [self.navigationController dismissModalViewControllerAnimated:YES];
}

/*!
 @abstract 登录按钮事件
 */
- (void)loginButtonEvent:(id)sender
{
    //发送请求时，一定要先更新数据库中最后登陆时间为当前时间，否则会被反复踢出
    NSDate* now = [NSDate date];
    long timestamp = [now timeIntervalSince1970];
    
    Option* option = [[Option alloc] init];
    option.name = @"lastQueryTime";
    option.value = [NSString stringWithFormat:@"%ld", timestamp];
    [[DBKit sharedDBKit] save:option];

    option.name = @"hadLogout";
    option.value = @"0";
    [[DBKit sharedDBKit] save:option];
    
    JSONRequest *loginRequest = [[JSONRequest alloc] initWithURLString:_JSON_URL_U_LOGIN];
    loginRequest.delegate = self;
    loginRequest.hudOn = true;
    loginRequest.hudTitle = _L(@"title_loading_01");
    [loginRequest setValue:_phoneTextField.text forParameter:@"mobile"];
    [loginRequest setValue:_passwordTextField.text forParameter:@"password"];
    [loginRequest asynchronous];
}


#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)responseData
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:responseData];

    //成功
    if (jmf.status == JMStatusSucceed) {

        //将用户的ID、token存入全局
        [Helper setUserDefaultsWithID:[jmf stringValue:@"id"] andToken:[jmf stringValue:@"token"] andName:[jmf stringValue:@"realName"]];

        //将用户ID、mobiel、password、token存入数据库
        Option* option = [[Option alloc] init];
        
        option.name = @"accountID";
        option.value = [jmf stringValue:@"id"];
        [[DBKit sharedDBKit] save:option];
        
        option.name = @"accountMobile";
        option.value = _phoneTextField.text;
        [[DBKit sharedDBKit] save:option];
        
        option.name = @"accountPassword";
        option.value = _passwordTextField.text;
        [[DBKit sharedDBKit] save:option];
        
        option.name = @"accountToken";
        option.value = [jmf stringValue:@"token"];
        [[DBKit sharedDBKit] save:option];
        
        //保存号码
        [Helper saveMobile:_phoneTextField.text];
        
        //跳转到welcome页面
        [self.navigationController dismissModalViewControllerAnimated:YES];
        
        //通知AppDelegate，隐藏视图和移除视图
        [[NSNotificationCenter defaultCenter] postNotificationName:@"Start_Main" object:nil];
        
        //极光推送服务
        //注销以前的设置，再设置当前登录后的用户的推送服务
        [APService setTags:nil alias:@""];
        [APService setTags:nil alias:[NSString stringWithFormat:@"%i", [_ACCOUNT_ID intValue]]];
        
        NSLog(@"LoginFormVC:195 设置APService的Alias为：%i", [_ACCOUNT_ID intValue]);
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

@end
